package com.example.library_demo.controller;


import com.example.library_demo.annotation.Auth;
import com.example.library_demo.common.Result;
import com.example.library_demo.dto.circulation.LendBookDTO;
import com.example.library_demo.dto.circulation.MyBorrowDTO;
import com.example.library_demo.dto.circulation.ReturnBookDTO;
import com.example.library_demo.entity.User;
import com.example.library_demo.enums.BizExceptionEnum;
import com.example.library_demo.enums.GlobalResponseResultEnum;
import com.example.library_demo.common.Result;
import com.example.library_demo.service.ICirculationService;
import com.example.library_demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Eric
 * @since 2024-11-27
 */
@RestController
@RequestMapping("/circulation")
public class CirculationController extends BaseController{

    @Autowired
    private ICirculationService circulationService;
    @Autowired
    private IUserService userService;

    @Auth
    @GetMapping("/my")
    public Result<List<MyBorrowDTO>> myBorrowList(){
        User user = super.getCurrentUser();
        List<MyBorrowDTO> list = circulationService.myBorrowList(user.getUserId());
        return Result.success(list);
    }

    @Auth
    @PutMapping("/lend")
    public Result<Void> lendBook( @RequestBody LendBookDTO lendBookDTO) {
        User user = super.getCurrentUser();
        circulationService.lendBooks(user.getUserId(), lendBookDTO);
        return Result.success();
    }

    @Auth
    @PutMapping("/return")
    public Result<Void> returnBook(@RequestBody ReturnBookDTO returnBookDTO) {
        User user = super.getCurrentUser();
        BigDecimal needPay = circulationService.returnBooks(user.getUserId(), returnBookDTO);
        if(needPay.equals(new BigDecimal(0))){
            return Result.success();
        } else {
            return Result.error(BizExceptionEnum.BALANCE_NOT_ENOUGH.getCode(),
                    BizExceptionEnum.BALANCE_NOT_ENOUGH.getMessage().replace("%money%",needPay.toPlainString()));
        }
    }
}

